package cn.lyn4ever.blogdemo.dowithoutifelse.config;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 微信公众号 “小鱼与Java”
 *
 * 原理很简单，我们写的类实现这个接口，具体可以查阅Spring生命周期相关内容
 * Spring会自动调用其中的setApplicationContext方法，传入Spring容器上下文
 * 我们就在这里把Spring上下文保存下来
 *
 * @date 2020/5/18
 * @auther Lyn4ever
 */
@Component
public class SpingContext implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    /**
     * 根据name从Spring容器中获取bean
     * @param name
     * @return
     */
    public static Object getBean(String name){
        return applicationContext.getBean(name);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        System.out.println("我保存了Spring上下文");
        applicationContext = applicationContext;
    }
}
